<template>
  <div class="checkout-page">
    <h1>确认订单</h1>
    
    <el-card class="checkout-card">
      <div slot="header">
        <span>订单商品</span>
      </div>
      <div v-if="loading" class="loading">
        <el-skeleton :rows="3" animated />
      </div>
      <div v-else-if="cart.length === 0" class="empty-cart">
        <i class="el-icon-shopping-cart-2"></i>
        <p>购物车为空，无法结算</p>
        <el-button type="primary" @click="$router.push('/')">去购物</el-button>
      </div>
      <div v-else>
        <div class="checkout-items">
          <div v-for="(item, index) in cart" :key="index" class="checkout-item">
            <span class="item-name">{{ item.name }}</span>
            <span class="item-price">¥{{ item.price.toFixed(2) }} × {{ item.quantity }}</span>
            <span class="item-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </el-card>
    
    <el-card class="checkout-card" v-if="cart.length > 0">
      <div slot="header">
        <span>配送信息</span>
      </div>
      <el-form ref="orderForm" :model="order" :rules="rules" label-width="100px">
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="order.address" placeholder="请输入收货地址"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="order.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="订单备注">
          <el-input type="textarea" v-model="order.remarks" placeholder="请输入订单备注，如配送时间等" rows="3"></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="checkout-card" v-if="cart.length > 0">
      <div slot="header">
        <span>支付方式</span>
      </div>
      <el-radio-group v-model="order.payType">
        <el-radio :label="1">微信支付</el-radio>
        <el-radio :label="2">支付宝</el-radio>
        <el-radio :label="3">货到付款</el-radio>
      </el-radio-group>
    </el-card>
    
    <div class="checkout-summary" v-if="cart.length > 0">
      <div class="summary-item">
        <span>商品总计：</span>
        <span>¥{{ cartTotal.toFixed(2) }}</span>
      </div>
      <div class="summary-item">
        <span>配送费：</span>
        <span>¥{{ (delivery.fee || 0).toFixed(2) }}</span>
      </div>
      <div class="summary-item total">
        <span>应付总额：</span>
        <span class="total-price">¥{{ (cartTotal + (delivery.fee || 0)).toFixed(2) }}</span>
      </div>
      
      <el-button type="primary" size="large" @click="submitOrder" :loading="submitting" :disabled="cart.length === 0">
        提交订单
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import { createOrder } from '@/api/order'

export default {
  name: 'Checkout',
  data() {
    return {
      loading: false,
      submitting: false,
      order: {
        address: '',
        phone: '',
        remarks: '',
        payType: 1
      },
      delivery: {
        fee: 5 // 默认配送费
      },
      rules: {
        address: [
          { required: true, message: '请输入收货地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapState(['cart', 'userInfo']),
    ...mapGetters(['cartTotal']),
    merchantId() {
      return this.cart.length > 0 ? this.cart[0].merchantId : null
    }
  },
  created() {
    // 检查是否已登录
    if (!this.userInfo || !this.userInfo.id) {
      this.$message.warning('请先登录')
      this.$router.push('/login?redirect=/checkout')
      return
    }
    
    // 检查购物车是否为空
    if (this.cart.length === 0) {
      this.$message.warning('购物车为空，无法结算')
      // 不要立即跳转，让用户可以查看提示消息
      setTimeout(() => {
        this.$router.push('/')
      }, 1500)
      return
    }
    
    // 初始化收货地址和电话
    if (this.userInfo) {
      this.order.address = this.userInfo.address || ''
      this.order.phone = this.userInfo.phone || ''
    }
  },
  methods: {
    submitOrder() {
      this.$refs.orderForm.validate(valid => {
        if (!valid) {
          return false
        }
        
        this.submitting = true
        
        // 准备订单数据
        const orderData = {
          userId: this.userInfo.id,
          merchantId: this.merchantId,
          address: this.order.address,
          phone: this.order.phone,
          remarks: this.order.remarks,
          totalAmount: this.cartTotal,
          deliveryFee: this.delivery.fee || 0,
          payAmount: this.cartTotal + (this.delivery.fee || 0),
          payType: this.order.payType,
          // 序列化商品数据
          items: JSON.stringify(this.cart.map(item => ({
            productId: item.id,
            name: item.name,
            price: item.price,
            quantity: item.quantity
          }))),
          // 默认为系统派单
          deliveryMode: 1
        }
        
        // 调用API创建订单
        createOrder(orderData)
          .then(res => {
            if (res.code === 200) {
              this.$message.success('订单提交成功')
              // 清空购物车
              this.$store.commit('clearCart')
              
              // 跳转到订单详情页面
              if (res.data && res.data.id) {
                this.$router.push(`/order/${res.data.id}`)
              } else {
                this.$router.push('/order')
              }
            } else {
              this.$message.error(res.message || '订单提交失败')
            }
          })
          .catch(err => {
            console.error('提交订单失败', err)
            this.$message.error('订单提交失败，请稍后重试')
          })
          .finally(() => {
            this.submitting = false
          })
      })
    }
  }
}
</script>

<style scoped>
.checkout-page {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

h1 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #303133;
}

.checkout-card {
  margin-bottom: 20px;
}

.loading {
  padding: 20px;
}

.empty-cart {
  padding: 30px;
  text-align: center;
}

.empty-cart i {
  font-size: 48px;
  color: #ccc;
}

.empty-cart p {
  margin: 15px 0;
  color: #909399;
}

.checkout-items {
  padding: 10px 0;
}

.checkout-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.checkout-item:last-child {
  border-bottom: none;
}

.item-name {
  flex: 2;
  font-weight: bold;
}

.item-price {
  flex: 1;
  text-align: center;
  color: #606266;
}

.item-subtotal {
  flex: 1;
  text-align: right;
  color: #ff6000;
}

.checkout-summary {
  background: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.summary-item.total {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #e0e0e0;
  font-weight: bold;
}

.total-price {
  font-size: 20px;
  color: #ff6000;
}

.el-button {
  margin-top: 20px;
  width: 100%;
}
</style> 